import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch

class MainPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class CreateBook(webapp.RequestHandler):
    def get(self):    
        request_url = 'http://www.blastcasta.com/feed-to-json.aspx?feedurl=http%3A//www.blastcasta.com/processedfeed.aspx%3Ffeedcode%3D%255Bbc_u1%255D<FEED_URL>%255B/bc_u1%255D%255Bbc_m1%255D-1%255B/bc_m1%255D%255Bbc_o%255D0%255B/bc_o%255D'    
        feed_url = self.request.get("feed_url")
        request_url = request_url.replace('<FEED_URL>', feed_url.replace('http:', 'http%25253A'))
        result = urlfetch.fetch(url=request_url)
        if result.content == "": raise Exception("The page at " + feed_url + " does not appear to contain any content!?!?! Are you sure you entered the correct url?")
        template_values = {'feed_url': feed_url,
                           'request_url': request_url,
                          'feed_json': result.content}
        path = os.path.join(os.path.dirname(__file__), 'create_book.html')
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [
                                      ('/', MainPage),
                                      ('/create_book', CreateBook)
                                      ],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()